package com.chilli.cosima.action.providermanager;

import java.io.File;
import java.util.Date;

import org.apache.struts2.ServletActionContext;

import com.chilli.cosima.action.BaseSupport;
import com.chilli.cosima.common.BussinessException;
import com.chilli.cosima.data.bean.Provider;
import com.chilli.cosima.service.ProviderService;

public class ProviderEditAction extends BaseSupport
{

	private static final long serialVersionUID = 6776035240589016696L;

	private int id;
	private Provider provider;
	private File myFile;
	private String myFileFileName;
	private ProviderService providerService;

	public String jumpPage()
	{

		Provider provider = providerService.findProviderById(id);

		if (null != provider)
		{
			this.provider = provider;
			return JUMP_PAGE;
		} else
		{
			logger.error("error");
			return ERROR;
		}

	}

	public String execute()
	{
		try
		{
			if (null != myFile)
			{
				String removeFileName = provider.getPicture();
				String imageFileName = new Date().getTime()
						+ getExtention(myFileFileName);

				File imageFile = new File(ServletActionContext
						.getServletContext().getRealPath(
								"/upload/images/provider")
						+ "/" + imageFileName);

				copy(myFile, imageFile);

				provider.setPicture(imageFileName);

				File removeFile = new File(ServletActionContext
						.getServletContext().getRealPath(
								"/upload/images/provider")
						+ "/" + removeFileName);

				if (removeFile.exists())
				{
					removeFile.delete();
				}
			}

			providerService.updateProvider(provider);
		} catch (BussinessException e)
		{
			logger.error("error", e);
		}
		return SUCCESS;
	}

	public int getId()
	{
		return id;
	}

	public void setId(int id)
	{
		this.id = id;
	}

	public Provider getProvider()
	{
		return provider;
	}

	public void setProvider(Provider provider)
	{
		this.provider = provider;
	}

	public ProviderService getProviderService()
	{
		return providerService;
	}

	public void setProviderService(ProviderService providerService)
	{
		this.providerService = providerService;
	}

	public File getMyFile()
	{
		return myFile;
	}

	public void setMyFile(File myFile)
	{
		this.myFile = myFile;
	}

	public String getMyFileFileName()
	{
		return myFileFileName;
	}

	public void setMyFileFileName(String myFileFileName)
	{
		this.myFileFileName = myFileFileName;
	}

}
